package com.ruoyi.web.controller.fund;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cost.domain.FundCostT;
import com.ruoyi.cost.service.IHouseCostTService;
import com.ruoyi.costQuery.domain.HouseCostT;
import com.ruoyi.costQuery.service.IHouseCostQueryTService;
import com.ruoyi.data.MD5;
import com.ruoyi.data.NumberData;
import com.ruoyi.door.domain.HouseDoorT;
import com.ruoyi.project.domain.ParameterSingleVO;
import com.ruoyi.project.service.IHouseProjectTService;
import com.ruoyi.util.SysParamKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/fund/cost")
public class HouseCostTController extends BaseController
{
    @Autowired
    private IHouseCostTService houseCostTService;
    @Autowired
    private IHouseCostQueryTService houseCostQueryTService;
    @Autowired
    private IHouseProjectTService houseProjectTService;
    /**
     * 查询户管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FundCostT fundCostT) throws Exception {
        startPage();
        if(fundCostT.getUserName()!=null){
            fundCostT.setUserName(MD5.encrypt(fundCostT.getUserName()));
        }
        List<FundCostT> list = houseCostTService.selectFundCostTList(fundCostT);
        for(FundCostT fundCostVO:list){
            fundCostVO.setPapersCode(MD5.decrypt(fundCostVO.getPapersCode()));
            fundCostVO.setUserName(MD5.decrypt(fundCostVO.getUserName()));
            fundCostVO.setTel(MD5.decrypt(fundCostVO.getTel()));
        }
        if(getDataTableSumJudge(list)){
            FundCostT fundCostVO = houseCostTService.selectFundCostTSum(fundCostT);
            fundCostVO.setAreaName("合计");
            list.add(fundCostVO);
        }
        return getDataTable(list);
    }

    /**
     * 导出缴费信息列表
     */
    @Log(title = "缴费信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FundCostT fundCostT) throws Exception {

        if(fundCostT.getUserName()!=null){
            fundCostT.setUserName(MD5.encrypt(fundCostT.getUserName()));
        }
        List<FundCostT> list = houseCostTService.selectFundCostTList(fundCostT);
        for(FundCostT fundCostVO:list){
            fundCostVO.setPapersCode(MD5.decrypt(fundCostVO.getPapersCode()));
            fundCostVO.setUserName(MD5.decrypt(fundCostVO.getUserName()));
            fundCostVO.setTel(MD5.decrypt(fundCostVO.getTel()));
        }
        if(getDataTableSumJudge(list)){
            FundCostT fundCostVO = houseCostTService.selectFundCostTSum(fundCostT);
            fundCostVO.setAreaName("合计");
            list.add(fundCostVO);
        }
        ExcelUtil<FundCostT> util = new ExcelUtil<FundCostT>(FundCostT.class);
        util.exportExcel(response, list, "缴费信息数据");
    }
    /**
     * 缴费
     */
    @Log(title = "缴费管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult insertCost(@RequestBody FundCostT fundCostT) throws Exception {
        fundCostT.setCreater(getUsername());
        if(fundCostT.getPapersCode()!=null){
            fundCostT.setPapersCode(MD5.encrypt(fundCostT.getPapersCode()));
        }
        if(fundCostT.getUserName()!=null){
            fundCostT.setUserName(MD5.encrypt(fundCostT.getUserName()));
        }
        if(fundCostT.getTel()!=null){
            fundCostT.setTel(MD5.encrypt(fundCostT.getTel()));
        }
        int costId = houseCostTService.updateFundCostT(fundCostT);
        HouseCostT houseCostVO = new HouseCostT();
        houseCostVO.setCostId(Long.valueOf(costId));
        return AjaxResult.success(houseCostVO);
    }
    /**
     * 扫码支付
     */
    @PutMapping("/weChatPay")
    @Transactional
    public AjaxResult weChatPay(@RequestBody FundCostT fundCostT) throws Exception {
        HouseCostT orderVO = new HouseCostT();
        orderVO.setOrderId(DateUtils.dateTimeNow() + fundCostT.getHouseId());
        orderVO.setUserName(MD5.encrypt(fundCostT.getUserName()));
        orderVO.setTel(MD5.encrypt(fundCostT.getTel()));
        orderVO.setPapersCode(MD5.encrypt(fundCostT.getPapersCode()));
        orderVO.setOrderMoney(fundCostT.getBudgetMoney());
        orderVO.setHouseId(fundCostT.getHouseId());
        orderVO.setOrderSts("0");
        HouseCostT vo = new HouseCostT();
        houseCostQueryTService.insertOrderInfo(orderVO);
        vo = houseCostQueryTService.selectOrderId(orderVO.getOrderId());
        String order_id = vo.getOrderId();
        int fee = (int) (vo.getOrderMoney() * 100);
        Double fee_display = vo.getOrderMoney();
        String business_id = vo.getHouseId();
        String body = "地址:" + fundCostT.getAreaName() +
                fundCostT.getGroupName() + fundCostT.getUnitName() + fundCostT.getDoorName() + "室" + vo.getOrderId() + "订单号";
        try {
            String pythonUrl = RuoYiConfig.getGetpythonAccount();
            /* String pythonUrl = "http://17.17.17.18:9527/back_service/do_unifiedorder_pay";*/
            URL url = new URL(pythonUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            String formdata =
                    "fee=" + URLEncoder.encode(String.valueOf(fee), "UTF-8") +
                            "&fee_display=" + URLEncoder.encode(String.valueOf(fee_display), "UTF-8") +
                            "&business_id=" + URLEncoder.encode(business_id, "UTF-8") +
                            "&body=" + URLEncoder.encode(body, "UTF-8") +
                            "&order_id=" + URLEncoder.encode(order_id, "UTF-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream out = conn.getOutputStream();
            out.write(formdata.getBytes());
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            String jsonString = response.toString();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> jsonMap = objectMapper.readValue(jsonString, Map.class);
            boolean success = (boolean) jsonMap.get("success");
            String orderid = (String) jsonMap.get("order_id");
            if (success == true) {
                String path = RuoYiConfig.getGetipAccount();
                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("addr", path + "weixin_" + orderid + ".png");
                return AjaxResult.success(map1);
            }
            System.out.println("python服务器的响应： " + response);
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(1);
    }
    /**
     * 获取户管理详细信息
     */
    @GetMapping(value = "/{doorId}")
    public AjaxResult getInfo(@PathVariable("doorId") Long doorId) throws Exception {
        FundCostT fundCostVO = houseCostTService.selectFundCostTByDoorId(doorId);
        fundCostVO.setPapersCode(MD5.decrypt(fundCostVO.getPapersCode()));
        fundCostVO.setUserName(MD5.decrypt(fundCostVO.getUserName()));
        fundCostVO.setTel(MD5.decrypt(fundCostVO.getTel()));
        return AjaxResult.success(fundCostVO);
    }

    /*缴费通知书*/
    @GetMapping(value = "getNote/{doorId}")
    public AjaxResult getNote(@PathVariable("doorId") Long doorId) throws Exception {
        FundCostT fundCostVO=houseCostTService.selectFundCostTByDoorId(doorId);
        fundCostVO.setUserName(MD5.decrypt(fundCostVO.getUserName()));
        fundCostVO.setBudgetMoneyDX(NumberData.makeUpperCaseSum(String.valueOf(fundCostVO.getBudgetMoney())));
        return AjaxResult.success(fundCostVO);
    }
}
